<template>
  <van-button
    v-if="value"
    round
    size="small"
    :loading="isFollowLoading"
    @click="onFollow"
    >已关注</van-button
  >
  <van-button
    type="info"
    color="#3296fa"
    round
    v-else
    size="small"
    icon="plus"
    :loading="isFollowLoading"
    @click="onFollow"
    >关注</van-button
  >
</template>

<script>
import { addFollow, deleteFollow } from "@/api/user";
export default {
  name: "FollowUser",
  data() {
    return {
      isFollowLoading: false // 关注按钮加载中
    };
  },
  props:{
    // 文章是否被关注了
    value:{
      type:Boolean,
      required:true
    },
    // 被关注的用户ID
    userId:{
      type:[Number,Object,String],
      required:true
    }
  },
  methods: {
    // 关注 或取消关注
    async onFollow() {
      // 是否登录了，登录了才可以操作
      if(!this.$store.state.user){
        this.$toast('请登录')
        return this.$router.push('/login?redirect='+this.$route.path)
      }

      // 显示关注加载中
      this.isFollowLoading = true;
      try {
        if (this.value) {
          // 关注了，要取消
          await deleteFollow(this.userId);
          this.$toast.success("取消成功");
        } else {
          // 没关注，要关注
          await addFollow(this.userId);
          this.$toast.success("关注成功");
        }
        // 更新视图
        this.$emit('input',!this.value)
      } catch (error) {
        this.$toast.fail("操作失败");
      }
      // 关闭显示加载中
      this.isFollowLoading = false;
    }
  }
};
</script>

<style lang="less" scoped></style>
